package protocol.transactions;


import protocol.XoneProtocol;
import protocol.XoneServiceCode;
import protocol.meta.CheckVersionInfo;
import Utils.XoneUtil;
import app.BaseApplication;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.netease.http.THttpRequest;
import com.netease.pkgRelated.ErrorToString;


public class CheckVersionTransaction extends XoneBaseTransaction {

    public CheckVersionTransaction() {
        super(TRANSACTION_TYPE_CHECK_VERSION);
    }
    @Override
    protected void onXoneTransactionSuccess(int code, Object obj) {
        if (obj != null && obj instanceof JsonElement) {
            JsonElement json = ((JsonElement)obj).getAsJsonObject().get("clientInfo");
            if (json != null) {
                Gson gson = new Gson();
                CheckVersionInfo info = gson.fromJson(json, CheckVersionInfo.class);
                if (info != null) {
                    long nv = 0l;
                    long ov = 0l;

                    nv = Long.parseLong(info.version.replace(".", ""));
                    ov = Long.parseLong(XoneUtil.getNumberVersion(BaseApplication.getAppInstance()).replace(".", ""));

                    if (nv > ov) {
                        notifyMessage(XoneServiceCode.TRANSACTION_SUCCESS, info);
                    } else {
                        notifyMessage(XoneServiceCode.TRANSACTION_SUCCESS, null);
                    }
                    return;
                }
            }
        }

        notifyError(XoneServiceCode.ERR_CODE_DATA_PARSE_EXCEPTION,
                ErrorToString.getString(XoneServiceCode.ERR_CODE_DATA_PARSE_EXCEPTION));

    }
        
    @Override
    public void onTransact() {
        THttpRequest request = XoneProtocol.getInstance().createCheckAppVersion();
        sendRequest(request);
    }

}
